from flask import Flask
import logging
import os

from logging.handlers import TimedRotatingFileHandler
from APP.API import init_view
from APP.Kafka import init_kafka, init_logDir
from config import envs

def config_logging(logDir):
    logging.basicConfig(level=logging.INFO)
    if os.path.exists(logDir) is False:
        os.makedirs(logDir)
    file_log_handler = TimedRotatingFileHandler(filename='log/detail.log', when='D', encoding='utf-8')
    formatter = logging.Formatter('%(message)s')
    file_log_handler.setFormatter(formatter)
    logging.getLogger().addHandler(file_log_handler)


def create_app(env):
    app = Flask(__name__)
    app.app_context().push()
    app.config.from_object(envs.get(env))  # 引入第三方文件
    config_logging(envs.get(env).logDir)
    init_kafka(in_bootstrap_servers=envs.get(env).kafka_in_bootstrap_servers)
    init_logDir(envs.get(env).kafkaDir)
    init_view(app)          # 引入视图
    logging.info("step2.初始化完成,已加载所有配置")
    return app